class Phong < ActiveRecord::Base
  attr_accessible :MaPhong, :TenPhongg, :MaLoai_id
  belongs_to :loai_phong, :class_name => "LoaiPhong", :foreign_key => "MaLoai_id"
  has_one  :QuanLy
  has_many :ct_phongs
  has_many :nhat_ky_den, :class_name => "NhatKy"
  has_many :nhat_ky_di, :class_name => "NhatKy"
  validates_length_of :MaPhong, :is => 4
  validates_uniqueness_of :MaPhong
  validates_presence_of :MaPhong, :TenPhongg, :MaLoai_id

  # hàm truyền mảng dữ liệu thông qua format csv    EXPORT
  def self.to_csv(phongs, options ={})
    CSV.generate(options) do |csv|
      csv << column_names
      phongs.each do |phong|
        csv << phong.attributes.values_at(*column_names)
      end
    end
  end
  # hàm truyền dữ liệu gọi lên vào database          IMPORT
  def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header,spreadsheet.row(i)].transpose]
      phong = find_by_id(row["id"]) || new
      phong.attributes = row.to_hash.slice(*accessible_attributes)
      return false if phong.invalid?
      phong.save!
    end
    true
  end
  # hàm truy xuất file upload lên
  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
      when '.csv' then Roo::Csv.new(file.path, nil, :ignore)
      when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
      when '.xlsx' then Roo::Excelx.new(file.path, nil, :ignore)
      else raise "Unknown file type: #{file.original_filename}"
    end
  end
end
